<?php

class SJB_AbstractCategorySearcher
{
	protected $field;

	public function SJB_AbstractCategorySearcher($field)
	{
		$this->field = $field;
	}

	public function getFieldSID($field)
	{
		$property = SJB_ListingManager::getPropertyByPropertyName($field);
		return $property->getSID();
	}

	public function getItems($request_data)
	{
        $items = $this->_get_Captions_with_Counts_Grouped_by_Captions($request_data);
        return $this->_decorateItems($items, $request_data);
	}

	protected function _get_Captions_with_Counts_Grouped_by_Captions($request_data)
	{
		$hash = md5('browse' . serialize($request_data) . SJB_Settings::getValue('enableBrowseByCounter') . $this->field['field']);
		$cache = SJB_Cache::getInstance();
		if ($res = $cache->load($hash)) {
			return $res;
		}
        $columns =  '?w as caption';
        if (SJB_Settings::getValue('enableBrowseByCounter')) {
			$columns .=  ', count(*) as count';
		}
        $sql = "select {$columns} from listings where sid in (?l) and ?w != '' group by ?w";
		$criteria = SJB_SearchFormBuilder::extractCriteriaFromRequestData($request_data);
		$searcher = SJB_ObjectMother::createListingSearcher();
		$ids = $searcher->getObjectsSIDsByCriteria($criteria);
		$res = array();
		if (count($ids) > 0) {
			$res = SJB_DB::query($sql, $this->field['field'], $ids, $this->field['field'], $this->field['field']);
		}
		$cache->save($res, $hash, array(SJB_Cache::TAG_LISTINGS));
        return $res;
	}

}

